package com.taxshare.seller.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxshare.mybatis.pager.PageHelp;
import com.taxshare.mybatis.pager.PageRequest;
import com.taxshare.mybatis.utils.DozerBeanUtil;
import com.taxshare.response.beans.Response;
import com.taxshare.seller.constant.ResultConstant;
import com.taxshare.seller.entity.AlsTenantInfoEntity;
import com.taxshare.seller.entity.excel.TenantInfoExcelEntity;
import com.taxshare.seller.mapper.AlsTenantInfoMapper;
import com.taxshare.seller.util.TransformationUtil;
import com.taxshare.seller.view.dto.ExcelDTO;
import com.taxshare.seller.view.dto.TenantInfoDTO;
import com.taxshare.tools.token.UserInfoUtil;
import com.taxshare.tools.util.ExcelUtil;
import com.taxshare.tools.util.UUIDUitl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * @ClassName: AlsTenantInfoService
 * @Description:
 * @author: Hai
 * @date: 2021/7/28 12:35
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
@Slf4j
public class AlsTenantInfoService extends ServiceImpl<AlsTenantInfoMapper, AlsTenantInfoEntity> {

    @Autowired
    CommService commService;

    /**
     * 分页查询
     * @param query
     * @return
     */
    public Response queryAlsTenantInfo(PageRequest<AlsTenantInfoEntity> query) {
        AlsTenantInfoEntity tenant = query.getInfo();
        QueryWrapper<AlsTenantInfoEntity> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(tenant.getProjectNo())) {
            queryWrapper.eq("project_no", tenant.getProjectNo());
        } /*else {
            List<String> taxNumbers = commService.getTaxNumbers();
            queryWrapper.in("project_no", taxNumbers);
        }*/
        if (StrUtil.isNotBlank(tenant.getCompanyName())) {
            queryWrapper.eq("company_name", tenant.getCompanyName());
        }
        if (StrUtil.isNotBlank(tenant.getCompanyNo())) {
            queryWrapper.eq("company_no", tenant.getCompanyNo());
        }
        if (StrUtil.isNotBlank(tenant.getProjectName())) {
            queryWrapper.eq("project_name", tenant.getProjectName());
        }
        queryWrapper.orderByDesc("create_time");
        IPage<AlsTenantInfoEntity> result = PageHelp.siamplePage(this, queryWrapper, query.getPage(), AlsTenantInfoEntity.class);
        return Response.success(result);
    }

    /**
     * 新增
     * @param entity
     * @return
     */
    public Response addAlsTenantInfo(AlsTenantInfoEntity entity) {
        entity.setUuid(UUIDUitl.UUID32(false));
        entity.setCreateUserid(UserInfoUtil.getUserID());
        entity.setUpdateUserid(UserInfoUtil.getUserID());
        baseMapper.insert(entity);
        return Response.success();
    }

    /**
     * 修改
     * @param entity
     * @return
     */
    public Response updateAlsTenantInfo(AlsTenantInfoEntity entity){
        entity.setUpdateUserid(UserInfoUtil.getUserID());
        baseMapper.updateById(entity);
        return Response.success();
    }

    /**
     * 删除
     * @param uuid
     * @return
     */
    public Response delAlsTenantInfo(String uuid){
        baseMapper.deleteById(uuid);
        return Response.success();
    }

    /**
     * 根据销方税号查询租户信息
     * @param sellerTaxNo
     * @return
     */
    public Response queryListBySellerTaxNo(String sellerTaxNo){
        List<AlsTenantInfoEntity> list = baseMapper.selectList(new QueryWrapper<AlsTenantInfoEntity>().eq("project_no", sellerTaxNo));
        return Response.success(list);
    }


    /**
     * 查询全部租户信息
     * @return
     */
    public Response queryAllTenantInfo() {
        List<AlsTenantInfoEntity> list = this.list(new QueryWrapper<>());
        return Response.success(list);
    }

    /**
     * 客户管理导出
     *
     * @param request
     * @param response
     */
    public void exportTenantInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        QueryWrapper<AlsTenantInfoEntity> queryWrapper = new QueryWrapper<>();
        String companyName = request.getParameter("companyName");
        String companyNo = request.getParameter("companyNo");
        String projectName = request.getParameter("projectName");
        String projectNo = request.getParameter("projectNo");
        if (StrUtil.isNotBlank(projectNo)) {
            queryWrapper.eq("project_no", projectNo);
        } else {
            List<String> taxNumbers = commService.getTaxNumbers();
            queryWrapper.in("project_no", taxNumbers);
        }
        if (StrUtil.isNotBlank(companyName)) {
            queryWrapper.eq("company_name", companyName);
        }
        if (StrUtil.isNotBlank(companyNo)) {
            queryWrapper.eq("company_no", companyNo);
        }
        if (StrUtil.isNotBlank(projectName)) {
            queryWrapper.eq("project_name", projectName);
        }
        List<TenantInfoExcelEntity> tenantInfoExcelEntities = baseMapper.queryTenantInfo(queryWrapper);
        for (int i = 0; i < tenantInfoExcelEntities.size(); i++) {
            String purchaserType = tenantInfoExcelEntities.get(i).getCompanyType();
            if ("1".equals(purchaserType)) {
                tenantInfoExcelEntities.get(i).setCompanyType("公司");
            }
            if ("2".equals(purchaserType)) {
                tenantInfoExcelEntities.get(i).setCompanyType("个人");
            }
        }
        List<String> cols = ExcelDTO.tenantInfoCols;
        HashMap<String, String> map = new HashMap<>();
        map.put("companyName", "购方公司名称");
        map.put("companyNo", "购方公司税号");
        map.put("companyType", "购方公司类型");
        map.put("companyBankAccount", "购方公司银行账号");
        map.put("companyBankAddress", "购方公司开户行");
        map.put("companyMobile", "购方公司电话");
        map.put("companyEmail", "购方公司邮箱");
        ExcelUtil.exportExcel(response, cols, map, tenantInfoExcelEntities, "客户管理信息");
    }

    /**
     * 客户管理导入
     *
     * @param multipartFile
     * @return
     */
    public Response importTenantInfo(MultipartFile multipartFile) {
        List<TenantInfoDTO> excelDTOList;
        try {
            excelDTOList = ExcelUtil.readExcel(multipartFile.getInputStream(), new TenantInfoDTO(), TenantInfoDTO.class);
        } catch (IOException e) {
            log.error("上传文件异常：", e);
            return Response.error(ResultConstant.RET_P0011_CODE, ResultConstant.RET_P0011_MSG);
        }
        for (TenantInfoDTO tenantInfoDTO : excelDTOList) {
            String companyName = tenantInfoDTO.getCompanyName();
            String projectTaxNo = tenantInfoDTO.getCompanyNo();
            if (StrUtil.isEmpty(tenantInfoDTO.getCompanyName())) {
                return Response.error(ResultConstant.RET_P0018CODE, "购方名称"+ResultConstant.RET_P0018_MSG);
            }
            if (StrUtil.isEmpty(tenantInfoDTO.getCompanyNo())) {
                return Response.error(ResultConstant.RET_P0018CODE, "税号"+ResultConstant.RET_P0018_MSG);
            }
            AlsTenantInfoEntity alsTenantInfoEntity = DozerBeanUtil.map(tenantInfoDTO, AlsTenantInfoEntity.class);
            alsTenantInfoEntity.setCompanyType(TransformationUtil.companyType(alsTenantInfoEntity.getCompanyType()));
            QueryWrapper<AlsTenantInfoEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("company_name", companyName);
            queryWrapper.eq("company_no", projectTaxNo);
            if (baseMapper.selectCount(queryWrapper) > 0) {
                baseMapper.update(alsTenantInfoEntity, queryWrapper);
            } else {
                alsTenantInfoEntity.setUuid(UUIDUitl.UUID32(false));
                baseMapper.insert(alsTenantInfoEntity);
            }
        }
        return Response.success();
    }
}
